﻿using System;
using BrainTechLLC.Silverlight.InputControls;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using BrainTechLLC.Silverlight.Controls;

namespace BrainTechLLC.Silverlight.ClientApplication
{
    public partial class Pager : UserControl
    {
        public event EventHandler<ObjectEventArgsNonRef<int>> EntryNumberChanged;
        public event EventHandler<ObjectEventArgsNonRef<int>> ItemCountChanged;

        public int EntryNumber { get; set; }
        public int ItemCount { get; set; }

        public Pager()
        {            
            InitializeComponent();
            EntryNumber = 0;
            ItemCount = 10;
            txtEntry.AttachFocusWatcher();
            txtItems.AttachFocusWatcher();
        }

        public ObservableCollection<T> GetCurrentPageCollection<T>(ObservableCollection<T> allItems)
        {
            if (allItems == null)
                return new ObservableCollection<T>();

            int entry = EntryNumber;
            int items = ItemCount;
            ObservableCollection<T> results = new ObservableCollection<T>();

            for (int n = Math.Min(entry, allItems.Count - 1); n >= 0 && n < allItems.Count; n++)
            {
                if (n - entry > items)
                    break;

                results.Add(allItems[n]);
            }

            return results;
        }

        private void txtEntry_KeyDown(object sender, KeyEventArgs e)
        {            
            if (e.Key == Key.Enter)
            {
                e.Handled = true;

                int n;
                if (!int.TryParse(txtEntry.Text, out n))
                    n = 0;

                EntryNumber = n;

                if (EntryNumberChanged != null)
                    EntryNumberChanged(this, new ObjectEventArgsNonRef<int>(n));
            }
        }

        private void txtItems_KeyDown(object sender, KeyEventArgs e)
        {            
            if (e.Key == Key.Enter)
            {
                e.Handled = true;

                int n;
                if (!int.TryParse(txtItems.Text, out n))
                    n = 0;

                ItemCount = n;

                if (ItemCountChanged != null)
                    ItemCountChanged(this, new ObjectEventArgsNonRef<int>(n));
            }
        }
    }
}